package com.gitee.dupe.ext.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import com.gitee.dolt.annotation.security.PreAuth;
import com.gitee.dolt.cache.repository.CacheOps;
import com.gitee.dolt.core.base.Result;
import com.gitee.dolt.core.util.BizAssert;
import com.gitee.dolt.security.model.AuthInfo;
import com.gitee.dolt.utils.web.ResponseUtils;
import com.gitee.dupe.common.properties.DupeProperties;
import com.gitee.dupe.common.properties.StaticProperties;
import com.gitee.dupe.oauth.dto.LoginDTO;
import com.gitee.dupe.oauth.granter.LoginNameTokenGranter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @author LYH
 */
@RestController
@RequestMapping("/b/system")
@Validated
@Api(value = "System", tags = "系统")
@RequiredArgsConstructor
@PreAuth("denyAll()")
public class SystemController {

    private final CacheOps cacheOps;
    private final DupeProperties dupeProperties;
    private final LoginNameTokenGranter loginNameTokenGranter;

    @GetMapping("/flushDb")
    @ApiOperation(value = "清空缓存数据库")
    public Result flushDb() {
        cacheOps.flushDb();
        return Result.ok();
    }

    @GetMapping("/getDeployInfo")
    @ApiOperation(value = "获取部署信息")
    public Result deployInfo() {
        return Result.ok(Dict.of("appStartTime", StaticProperties.appStartTime));
    }


    @GetMapping("/getUserToken")
    @ApiOperation(value = "获取用户token")
    public Result deployInfo(@RequestParam String loginName) {
        AuthInfo authInfo = loginNameTokenGranter.grant(new LoginDTO().setLoginName(loginName));
        return Result.ok(authInfo);
    }

    @ResponseBody
    @GetMapping("/downloadLogFile")
    @ApiOperation(value = "下载当前日志文件", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void downloadLogFile(HttpServletResponse response) {
        DupeProperties.LogProperties logProperties = dupeProperties.getLog();
        File file = FileUtil.file(logProperties.getCurrentLogPath());
        BizAssert.isTrue(FileUtil.exist(file), "日志文件不存在");
        ResponseUtils.renderFile(response, file);
    }


}
